package cn.house.rent.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@RequestMapping("captcha")
public class Captcha {

    @RequestMapping("/getCaptcha")
    public static void getCaptcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*hutool生成图片验证码*/
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(350, 100, 4, 4);
        //获取生成的验证码
        String code = captcha.getCode();
        System.out.println("code = " + code);
        //将验证码存入session 以便登录验证
        req.getSession().setAttribute("captcha", code);
        //图形验证码写出，可以写出到文件，也可以写出到流
        ServletOutputStream outputStream = resp.getOutputStream();
        captcha.write(outputStream);//写出到流
        outputStream.close();
    }
}
